<template>
  <div>
    <van-nav-bar
  title="购物车"
  left-arrow
/>
    <van-card
      v-for="(item, index) in $store.state.cartlist"
      :key="index"
      :price="item.price"
      desc="描述信息"
      :title="item.title"
      :thumb="item.pic"
    >
      <template #num> 
        <van-stepper v-model="item.num" @change="unchecked" /> 
      </template>
      <template #desc>
        <van-checkbox v-model="item.checked"></van-checkbox>
      </template>
      <template #footer>
    <van-button size="mini" @click="remove(index)" type="danger">删除</van-button>
    <!-- <van-button size="mini">按钮</van-button> -->
  </template>
    </van-card>
    <van-submit-bar :price="prices" button-text="提交订单" style="bottom:50px">
      <van-checkbox v-model="checked" @change="checkAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import Vue from "vue";
import { Checkbox, CheckboxGroup } from "vant";

Vue.use(Checkbox);
Vue.use(CheckboxGroup);
export default {
  data() {
    return {
        checked:false
    };
  },
  methods: {
      // 全选的方法
      checkAll(){
        //遍历购物车中的数据
        this.$store.state.cartlist.forEach(item => {
          // console.log(item);
          item.checked = this.checked;
        });
      },
      //反选的方法
      unchecked(){
        //先遍历数据,得到选中数据的长度
        let check =  this.$store.state.cartlist.filter(item=>{
          return item.checked == true;
        })
        // console.log(check.length);
          //判断选中的选中数据的长度,是否等于数据的总长度
          if (check.length == this.$store.state.cartlist.length) {
              this.checked = true;
          }else{
            this.checked = false;
          }
      },
      //删除购物车中的数据
      remove(index){
        // console.log(index);
        this.$store.commit('del',index);
        this.$toast.success('删除成功');
      }
    },
    computed:{
        //计算购物车中选中商品的总价
      prices(){
        let nums = 0;
        this.$store.state.cartlist.forEach(item => {
          // console.log(item);
          if (item.checked == true) {
            return nums += item.price * item.num;
          }
        })
        return nums * 100;
      }
    }
};
</script>